//
//  EmojiViewController.swift
//  DEMO4
//
//  Created by J on 16/5/8.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
private let reuseIdentifier = "reuseIdentifier"
class EmojiViewController: UIViewController {

    var emoticonDidSelectedCallBack: (emoticon:Emoticon)->()//传递选中表情模型
    init(callBack:(emoticon:Emoticon)->()){

        self.emoticonDidSelectedCallBack = callBack
        super.init(nibName: nil, bundle: nil)
    }
    
   
    override func viewDidLoad() {
        super.viewDidLoad()

        //1.添加子控件
        view.addSubview(collecitonView)
        view.addSubview(toolBar)
        
        //2.布局子控件
        collecitonView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        var cons = [NSLayoutConstraint]()
        
        let dict = ["collecitonView":collecitonView,"toolBar":toolBar]
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collecitonView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: dict)
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collecitonView]-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: dict)
        
        view.addConstraints(cons)
        
        EmoticonsPakage.loadPackages()
        
    }

  
    
    private lazy var collecitonView : UICollectionView = {
       let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonFlowLayout())
        //注册cell 
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
        
    }()
    
    
    
    private lazy var toolBar : UIToolbar = {
       let bar = UIToolbar()
        bar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        var  index = 0
        
        for title in ["最近","默认","emoji","浪小花"]{
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(itemClick))
            item.tag = index
            index+=1
        items.append(item)
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.popLast()
        bar.items = items
        return bar
    }()
    
    
    func itemClick(item:UIBarButtonItem){//点击toolbar的item
        print(item.tag)
        collecitonView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: item.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }

    
    private lazy var packages : [EmoticonsPakage] = EmoticonsPakage.loadPackages()
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension EmojiViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return packages.count
    }
    
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        
        return packages[section].emoticons?.count ?? 0
    }
    

     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! EmoticonCell
 
        //1.取出对应组
        let package = packages[indexPath.section]
        //2.取出对应组对应模型
        let emoticon = package.emoticons![indexPath.item]
        //3.赋值给cell
        cell.emoticon = emoticon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        emoticonDidSelectedCallBack(emoticon: emoticon)
        
    }
    
    
}





class EmoticonCell: UICollectionViewCell {
    
    var emoticon : Emoticon? {
        
        didSet{
            //1.判断是否是图片表情
            if emoticon?.chs != nil {
                iconButton.setImage(UIImage(contentsOfFile:emoticon!.imagePath!), forState: UIControlState.Normal)
            }else{
                iconButton.setImage(nil, forState: UIControlState.Normal)

            }
            //2.设置emoji表情
            iconButton.setTitle(emoticon?.emojiStr ?? "", forState: UIControlState.Normal)
        
            //3.判断是否是删除按钮
            if emoticon!.isRemoveButton{
                iconButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                iconButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    


    private func setupUI(){
        
        contentView.addSubview(iconButton)
        
    }
    
    // MARK: -- iconButton
    private lazy var  iconButton: UIButton = {
        
     let btn = UIButton(type: UIButtonType.Custom)
        btn.frame = CGRectInset(self.contentView.bounds, 4, 4)
        btn.backgroundColor = UIColor.whiteColor()
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        btn.adjustsImageWhenHighlighted = false
        btn.userInteractionEnabled = false
        return btn
        
    }()
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}




private class EmoticonFlowLayout: UICollectionViewFlowLayout{
    
    private override func prepareLayout() {
        super.prepareLayout()
        
        //设置cell属性
        let width = collectionView!.bounds.width / 7.0
        itemSize = CGSize(width: width, height: width)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        //设置collectionView相关属性
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        let y = (collectionView!.bounds.height - 3 * width) * 0.49999
        collectionView?.contentInset = UIEdgeInsetsMake(y, 0, y, 0)
        
        
    }
    
    
}